import { Controller, Get, Post, Body, Patch, Param, Delete, UploadedFile, UseInterceptors, UploadedFiles } from '@nestjs/common';
import { OtaService } from './ota.service';
import { AnyFilesInterceptor, FileInterceptor } from '@nestjs/platform-express';
import { storage } from './uploadStorage';
import * as crypto from 'crypto';
import * as fs from 'fs';
interface FirmwareFile {
  type: string;
  filename: string;
  version: string;
}
interface FirmwareInfo {
  size: number|string;
  date: string;
  files: FirmwareFile[];
  md5: string;
}
enum UpgradeStatus {
  IDLE = "idle",
  RUNNING = "running",
  SUCCESS = "success",
}
interface UpgradeInfo {
  status: UpgradeStatus;
  progress: number;
  message: string;
}
@Controller('ota')
export class OtaController {
  constructor(private readonly otaService: OtaService) {}

  public firmwareInfo: FirmwareInfo = {
    size: "",
    date: "",
    md5: "",
    files:[
      {
        type: "1",
        filename: "1",
        version: "1.0.0",
      },
      {
        type: "1",
        filename: "1",
        version: "1.0.0",
      },
      {
        type: "1",
        filename: "11",
        version: "1.0.0",
      },
    ]
  };


  @Post('file_upload')
  @UseInterceptors(AnyFilesInterceptor({ storage }))
  uploadAnyFiles(@UploadedFiles() files: Array<Express.Multer.File>, @Body() body) {
    console.log(files,"files");
    const decodedFilename = Buffer.from(files[0].originalname, 'latin1').toString('utf8');
    const bytes = files[0].size;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const fileContent = fs.readFileSync(files[0].path);
    const md5 = crypto.createHash('md5').update(fileContent).digest('hex');
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    const formattedSize = `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
    this.firmwareInfo.size = formattedSize;  
    this.firmwareInfo.date = new Date().toLocaleString();
    this.firmwareInfo.files[0].type = files[0].mimetype;
    this.firmwareInfo.files[0].filename = decodedFilename;
    this.firmwareInfo.files[0].version = body.version;
    this.firmwareInfo.md5 = md5;
    return {
      code: 200,
      message: '上传成功',
      data: {
        ...files,
        originalname: decodedFilename
      },
    };
  }

  //获取固件文件信息
  @Post('/fw_info')
  firmware_get() {
    return {
      code: 200,
      message: '获取成功',
      data: this.firmwareInfo,
    };
  }

    getStatus(status:string){
        switch(status){
            case "idle":
                return UpgradeStatus.IDLE;
            case "running":
                return UpgradeStatus.RUNNING;
            case "success":
                this.requestNum = 0;
                return UpgradeStatus.SUCCESS;
        }
    }
   
   public requestNum = 0;
   public upgradeInfo:UpgradeInfo = {
    status:this.getStatus("idle"),
    progress:0,
    message:"upgrade cp",
   }

  // 固件升级
  @Post('/upgrade')
  upgrade(@Body() body: any){ 
    return {
      code: 200,
      }
    };

    // 查询固件升级状态
    @Post('/upgrade_status')
    upgrade_status(){
      this.requestNum++;
      switch(this.requestNum){
        case 1:
          this.upgradeInfo.status = this.getStatus("running");
          this.upgradeInfo.message = "upgrade cp";
          this.upgradeInfo.progress = 50;
          break;
        case 2:
          this.upgradeInfo.status = this.getStatus("success");
          this.upgradeInfo.message = "upgrade success";
          this.upgradeInfo.progress = 100;
          break;
      }
      return {
        code: 200,
        data:this.upgradeInfo,
      }
    }


    // 裸包升级
    @Post('/upgrade_bare')
    upgrade_raw(){
      return {
        code: 200,
      }
    }


    // 获取裸包升级状态
    @Post('/upgrade_status_bare')
    upgrade_bare_status(){
      this.requestNum++;
      switch(this.requestNum){
        case 1:
          this.upgradeInfo.status = this.getStatus("running");
          this.upgradeInfo.message = "upgrade cp";
          this.upgradeInfo.progress = 50;
          break;
        case 2:
          this.upgradeInfo.status = this.getStatus("success");
          this.upgradeInfo.message = "upgrade success";
          this.upgradeInfo.progress = 100;
          break;
      }
      return {
        code: 200,
        data:this.upgradeInfo,
      }
    }

    // 获取HOST列表
    @Post('/host_relevance_get')
    host_list(){
     return this.otaService.getHostList();
    }

    // 切换HOST
    @Post('/host_relevance_select')
    switch_host(@Body('id') id: number){
      return this.otaService.switchHost(id);
    }

    // 删除HOST
    @Post('/host_relevance_del')
    delete_host(@Body('id') id: number){
      return this.otaService.deleteHost(id);
    }
  }

